using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Text;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.InsightWebControls;
using PHSRAG.Insight21.Policy;
using PHSRAG.Insight21.SearchContext;
using PHSRAG.Utility;
using Constant = PHSRAG.Insight21.InsightUtilities.Constants;
using Helper = PHSRAG.WebControls.Helper;

namespace PHSRAG.Insight21.Agreements
{
    /// <summary>
    /// Salaries Overview page is used to display Salary information of employees based 
    /// on the funds their salary is getting paid from.
    /// Page consists of Header Control, 
    ///		Sub Navigation Control for Agreements, 
    ///		Search Control for Agreements, 
    ///		Annunciator( displays messages on Page) , 
    ///		Activityindicator ( interactive way of communication to user that pages will take some time to load info )
    ///		Data Grid(to display salary information )
    ///	The same page is used to display Overview and Details information based on the Incoming data key, if key is 
    ///	present details information is displayed otherwise overview information is displayed
    ///	---modified: 08/08/2007 - added switch to report title (details or overview) JML
    /// </summary>
    public partial class Migrated_SalariesOverview : SalariesOverview
    {
        #region Constants

//		private const string TotalAnnualRate		= "TotalAnnualRate";
//		private const string TotalMonthlyRate		= "TotalMonthlyRate";
        private const string CommandName = "LinkLaborDistribution";
        private const string ExcelReportControlFilePath = "../../Agreements/Reports/SalaryOverviewExcel.ascx";

        private const string MinimumDate = "1/1/1900";
        private const string ReportTitle = "Salaries Overview";
        private const string TotalCommittedFringe = "TotalCommittedFringe";
        private const string TotalCommittedSalary = "TotalCommittedSalary";
        private const string TotalPaidToDate = "TotalPaidToDate";
        private const string TotalTotalCommitted = "TotalTotalCommitted";

        private static string CumLevelKey = "CumLevelKey_71E2ECBB-0308-45bc-8986-7D30ADEF3022";
        private static string IncomingFundNumberKey = "IncomingFundNumberKey_71E2ECBB-0308-45bc-8986-7D30ADEF3022";
        private static string SalaryBudgetYearKey = "SalaryBudgetYearKey_71E2ECBB-0308-45bc-8986-7D30ADEF3022";
        private static string SearchCriteriaVersionKey = "SearchCriteriaVersion_71E2ECBB-0308-45bc-8986-7D30ADEF3022";

        private bool isDetail;

        #endregion

        private ICachePolicy cachePolicy;
        private ICachePolicy pageCachePolicy;

        #region Private Properties

        /// <summary>
        /// Gets/sets an integer value indicating the search criteria version. 
        /// The version number changes when the search criteria changes.  This signals the page to re-build its
        /// cache. This and all properties required to re-establish the page are stored as name / value pairs in
        /// a hash table stored in the page cache under the key Keys.SalariesOverviewPageKey.
        /// This enables the page to re-establish its state with minimal IO to what it was when
        /// the user last visited it.
        /// </summary>
        private int SearchCriteriaVersion
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.SalariesOverviewPageKey) as Hashtable;
                return (h == null || h[SearchCriteriaVersionKey] == null) ? 0 : (int) h[SearchCriteriaVersionKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.SalariesOverviewPageKey) as Hashtable ?? new Hashtable();
                h[SearchCriteriaVersionKey] = value;
                pageCachePolicy.Cache(Keys.SalariesOverviewPageKey, h);
            }
        }

        /// <summary>
        /// Get the Salary Distributions that the logged-in user has access to. The list of Salary Distributions are 
        /// maintained by the SalaryDistributions business object within its data container. The business object is cached.
        /// Based on Summary pages that was visited first set FundStatus and AgreementStatus keys,
        /// if comming from AgreementSummary set the FundStatusId key to 0, default to bring all funds
        /// and if comming from financialSummay set the AgreementStatusId key to "", db gets all agreements for this Search key.
        /// </summary>
        private SalaryDistributions SalaryDistributions
        {
            get
            {
                CommonSearchContext searchContext = (CommonSearchContext) cachePolicy.GetCachedObject(CommonSearchContext.CacheKey);

                SearchCriteria searchCriteria;

                if (searchContext != null)
                {
                    searchCriteria = searchContext.GetSearchCriteria(Page.Request.Url.ToString());
                }
                else
                {
                    throw (new Exception("Session Expired, Please Logout and Log In again"));
                }

                int searchVersion = searchCriteria.Version;

                SalaryDistributions salaryDistributions = null;

                if ((searchVersion == SearchCriteriaVersion) && (searchVersion != -1))
                {
                    salaryDistributions =
                        ResultsCache.GetObject(cachePolicy, SalaryDistributions.CacheKey) as SalaryDistributions;
                }

                if (salaryDistributions == null)
                {
                    salaryDistributions = new SalaryDistributions();

                    bool ignoreFundStatus = false;
                    bool ignoreAgreementStatus = false;
                    // Based on Summary pages that was visited first set FundStatus and AgreementStatus keys,
                    // if comming from AgreementSummary set the FundStatusId key to 0, default to bring all funds
                    // and if comming from financialSummay set the AgreementStatusId key to "", db gets all agreements for this Search key.
                    if (ReferingSummaryPage == Constant.ModulePages.AgreementSummary)
                    {
                        //if the fund status isn't is search criteria ignore it
                        if (searchCriteria[Constant.FundStatusIDKey] == null)
                        {
                            ignoreFundStatus = true;
                        }
                    }
                    else if (ReferingSummaryPage == Constant.ModulePages.FinancialSummary)
                    {
                        if (searchCriteria[Constant.AgreementStatusIDKey] == null)
                        {
                            ignoreAgreementStatus = true;
                        }
                    }

                    salaryDistributions.Load(
                        DataAccess.GetConnectionString(), Session.SessionID
                        , searchCriteria, refreshDates.GLPostAsOfDate.ToShortDateString()
                        , IncomingFundNumber, ignoreFundStatus, ignoreAgreementStatus, isDetail, CumLevel, BudgetYear);

                    SearchCriteriaVersion = searchVersion;

                    ResultsCache.SetObject(cachePolicy, SalaryDistributions.CacheKey, salaryDistributions);
                }

                return salaryDistributions;
            }
        }

        /// <summary>
        /// Gets and sets the name of the agreement module summary (Agreement or Financial) page user last navigated from
        /// using the page cache policy.
        /// Returns an empty string if the value fetched from the pagecache policy is null. 
        /// </summary>
        private string ReferingSummaryPage
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.SalariesOverviewPageKey) as Hashtable;
                return (h == null || h[Keys.SummaryPageReferrerKey] == null) ? string.Empty : (string) h[Keys.SummaryPageReferrerKey];
            }

            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.SalariesOverviewPageKey) as Hashtable ?? new Hashtable();
                h[Keys.SummaryPageReferrerKey] = value;
                pageCachePolicy.Cache(Keys.SalariesOverviewPageKey, h);
            }
        }

        /// <summary>
        /// Gets and sets the name of the page user last navigated from. This is required 
        /// to track which Overview or detail pages was visited prior to this page. 
        /// Returns an empty string if the value fetched from the pagecache policy is null. 
        /// </summary>
        private string ReferingPage
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.SalariesOverviewPageKey) as Hashtable;
                return (h == null || h[Keys.PageReferrerKey] == null) ? string.Empty : (string) h[Keys.PageReferrerKey];
            }

            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.SalariesOverviewPageKey) as Hashtable ?? new Hashtable();
                h[Keys.PageReferrerKey] = value;
                pageCachePolicy.Cache(Keys.SalariesOverviewPageKey, h);
            }
        }

        #region Current Page Index

        /// <summary>
        /// Get/Set the current page index in pagecache policy, 
        /// Derive class datagrid use this to set the Current page index for display. 
        /// This information persists across page loads.
        /// </summary>
        protected int CurrentPageIndex
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.SalariesOverviewPageKey) as Hashtable;
                return (h == null || h[Keys.CurrentPageIndexKey] == null) ? 0 : (int) h[Keys.CurrentPageIndexKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.SalariesOverviewPageKey) as Hashtable ?? new Hashtable();
                h[Keys.CurrentPageIndexKey] = value;
                dataGrid.CurrentPageIndex = value;
                pageCachePolicy.Cache(Keys.SalariesOverviewPageKey, h);
            }
        }

        #endregion

        #region Incomming Fund Number

        /// <summary>
        /// Gets/Sets fund number passed down from other pages that post to this, 
        /// set once on page load, is stored in pagecache to be utilized
        /// across postbacks
        /// </summary>
        private string IncomingFundNumber
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.SalariesOverviewPageKey) as Hashtable;
                return (h == null || h[IncomingFundNumberKey] == null) ? string.Empty : h[IncomingFundNumberKey].ToString();
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.SalariesOverviewPageKey) as Hashtable ?? new Hashtable();
                h[IncomingFundNumberKey] = value;
                pageCachePolicy.Cache(Keys.SalariesOverviewPageKey, h);
            }
        }

        #endregion

        #region Cum Level

        /// <summary>
        /// Gets/Sets cumulative level passed down from other pages that post to this, 
        /// set once on page load, is stored in pagecache to be utilized
        /// across postbacks
        /// </summary>
        private int CumLevel
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.SalariesOverviewPageKey) as Hashtable;
                return (h == null || h[CumLevelKey] == null) ? 0 : (int) h[CumLevelKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.SalariesOverviewPageKey) as Hashtable ?? new Hashtable();
                h[CumLevelKey] = value;
                pageCachePolicy.Cache(Keys.SalariesOverviewPageKey, h);
            }
        }

        #endregion

        #region BudgetYear

        /// <summary>
        /// Gets/Sets budget year passed down from other pages that post to this, 
        /// set once on page load, is stored in pagecache to be utilized
        /// across postbacks
        /// </summary>
        private int BudgetYear
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.SalariesOverviewPageKey) as Hashtable;
                return (h == null || h[SalaryBudgetYearKey] == null) ? 0 : (int) h[SalaryBudgetYearKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.SalariesOverviewPageKey) as Hashtable ?? new Hashtable();
                h[SalaryBudgetYearKey] = value;
                pageCachePolicy.Cache(Keys.SalariesOverviewPageKey, h);
            }
        }

        #endregion

        #endregion

        #region Event Handlers

        #region OnPageLoad

        /// <summary>
        ///  Handler for the event raised when the page is being loaded.
        ///  Identify the context in which the page is being loaded (Overview or Details)
        ///  and load the appropriate controls and data on the page
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                downloadBar.SQLReportName = "SalaryReport";

                annunciator.Message = string.Empty;
                annunciator.Title = string.Empty;

                // check for AgreementsDetail, if present this page behaves as 
                // salaries detials page showing the info for incoming fund number in
                // Agreements details key.
                Hashtable h2 = cachePolicy.GetCachedObject(Constant.AgreementsConstants.AgreementDetailsKey) as Hashtable;
                isDetail = h2 != null && h2.Count > 0;

                if (!IsPostBack)
                {
                    if (isDetail)
                    {
                        pageLabel.Text = "Salary Details | As Of&nbsp;" + DateTime.Now.ToShortDateString();

                        breadCrumb.Add(@"Salary Details"
                            , Settings.GetKeyValue(@"SubNavigation.Agreements.SalaryOverviewURL", string.Empty)
                            , Settings.GetKeyValue(@"BreadCrumb.DetailPageLevel", AgreementConstants.DetailPageLevelValue));

                        agreementsSubNavigation.EnableOverviewNavigation = searchFilter.Visible = false;
                        agreementDetailsSubNavigation.SelectedLink = AgreementDetailsSubNavigation.SalaryDetailCommand;

                        if (h2[Keys.FundNumberKey] == null)
                        {
                            throw (new Exception("Salaries Details requires fund number"));
                        }

                        string incomingFundNumber = string.Empty;
                        string selectedBudgetDetailFundNumber = h2[Keys.SelectedBudgetDetailFundNumberKey] as String;
                        CumLevel = (h2[Keys.CumulativeKey] != null) ? Convert.ToInt32(h2[Keys.CumulativeKey]) : 1;

                        if (!string.IsNullOrEmpty(selectedBudgetDetailFundNumber))
                        {
                            //we came in from the budget details page and a fund was selected so use that one
                            //remove from the dictionary, and recache the dictionary.
                            incomingFundNumber = selectedBudgetDetailFundNumber;
                            h2.Remove(Keys.SelectedBudgetDetailFundNumberKey);
                            pageCachePolicy.Cache(Constant.AgreementsConstants.AgreementDetailsKey, h2);
                        }
                        else
                        {
                            incomingFundNumber = (string) h2[Keys.FundNumberKey];
                            h2[Keys.RefreshBudgetDetailDataKey] = true;
                            cachePolicy.Cache(Constant.AgreementsConstants.AgreementDetailsKey, h2);
                        }

                        if (IncomingFundNumber != incomingFundNumber)
                        {
                            IncomingFundNumber = incomingFundNumber;
                            SearchCriteriaVersion = -1;
                        }

                        int budgetYear = 0;
                        //assign the budget year to the selected budget year from the budget details page
                        if (h2[Keys.SelectedBudgetDetailsYearKey] != null)
                        {
                            BudgetYear = (int) h2[Keys.SelectedBudgetDetailsYearKey];
                            h2.Remove(Keys.SelectedBudgetDetailsYearKey);
                            pageCachePolicy.Cache(Constant.AgreementsConstants.AgreementDetailsKey, h2);
                        }
                        else if (h2[Keys.BudgetYearKey] != null)
                        {
                            BudgetYear = (int) h2[Keys.BudgetYearKey];
                        }

                        projectHeaderBar.LoadProjectHeader(incomingFundNumber, -1, budgetYear);
                    }
                    else
                    {
                        agreementDetailsSubNavigation.Visible = projectHeaderBar.Visible = false;

                        if (IncomingFundNumber != string.Empty)
                        {
                            SearchCriteriaVersion = -1;
                            IncomingFundNumber = string.Empty;
                        }
                        breadCrumb.Add(@"Salary Overview"
                            , Settings.GetKeyValue(@"SubNavigation.Agreements.SalaryOverviewURL", string.Empty)
                            , Settings.GetKeyValue(@"BreadCrumb.DetailPageLevel", AgreementConstants.DetailPageLevelValue));

                        pageLabel.Text = "Salary Overview | As Of&nbsp;" + DateTime.Now.ToShortDateString();

                        agreementsSubNavigation.SelectedOverviewLink = AgreementsSubNavigation.SalaryOverviewCommand;
                    }

                    dataGrid.PageSize = Settings.GetKeyValue("DataGrid.ItemsPerPage", 20);
                }
                else
                {
                    agreementsSubNavigation.EnableOverviewNavigation = !isDetail;
                }

                LoadDataGrid();
                header.ModuleName = Constant.Modules.Agreements;
            }
            catch (Exception excp)
            {
                annunciator.Message = ExceptionReport.GetExceptionInfo(excp, false);
            }
        }

        #endregion

        #region Pager Above and Below Datagrid events

        protected void OnFirstPage(object sender, CommandEventArgs e)
        {
            try
            {
                CurrentPageIndex = 0;
                LoadDataGrid();
            }
            catch (Exception excp)
            {
                annunciator.Message = ExceptionReport.GetExceptionInfo(excp, false);
            }
        }

        protected void OnLastPage(object sender, CommandEventArgs e)
        {
            try
            {
                CurrentPageIndex = pagerAboveDatagrid.PageCount - 1;
                LoadDataGrid();
            }
            catch (Exception excp)
            {
                annunciator.Message = ExceptionReport.GetExceptionInfo(excp, false);
            }
        }

        /// <summary>
        /// Purges the cache and sets the correct search context level before the breadcrumb performs a redirect.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnNavigate(object sender, CommandEventArgs e)
        {
            if (((CommandEventArgs) (e.CommandArgument)).CommandName == Convert.ToString((int) SearchCriteria.Level.Summary))
            {
                //set the search context's level to the correct level
                CommonSearchContext searchContext = (CommonSearchContext) cachePolicy.GetCachedObject(CommonSearchContext.CacheKey);
                searchContext.CurrentLevel = SearchCriteria.Level.Summary;
            }
            PurgeCache();
        }

        protected void OnNextPage(object sender, CommandEventArgs e)
        {
            try
            {
                ++CurrentPageIndex;
                LoadDataGrid();
            }
            catch (Exception excp)
            {
                annunciator.Message = ExceptionReport.GetExceptionInfo(excp, false);
            }
        }

        protected void OnPreviousPage(object sender, CommandEventArgs e)
        {
            try
            {
                --CurrentPageIndex;
                LoadDataGrid();
            }
            catch (Exception excp)
            {
                annunciator.Message = ExceptionReport.GetExceptionInfo(excp, false);
            }
        }

        #endregion

        #region Downloadbar event handlers

        /// <summary>
        /// Invoked by the download bar when it catches an exception.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        protected void OnDownloadFailed(object sender, CommandEventArgs e)
        {
            annunciator.Title = "Following error(s) occurred while downloading";
            annunciator.Message = ExceptionReport.GetExceptionInfo((Exception) e.CommandArgument, false);
        }

        #endregion

        #region DataGrid events

        protected void OnItemCreated(object sender, DataGridItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.Header)
                {
                    SalaryDistributions salaryDistributions = SalaryDistributions;

                    Label sortSymbol = new Label();

                    sortSymbol.Text = salaryDistributions.SortAscending ? Constant.SortAscendingText : Constant.SortDescendingText;
                    sortSymbol.Font.Name = Constant.SortSymbolFontName;

                    Hashtable columnMap = new Hashtable();
                    foreach (DataGridColumn column in dataGrid.Columns)
                    {
                        columnMap[column.SortExpression] = dataGrid.Columns.IndexOf(column);
                    }

                    string sortColumn = salaryDistributions.SortColumn;

                    if (columnMap.ContainsKey(sortColumn))
                    {
                        (e.Item.Cells[(int) columnMap[sortColumn]]).Controls.Add(sortSymbol);
                    }
                }
            }
            catch (Exception excp)
            {
                annunciator.Message = ExceptionReport.GetExceptionInfo(excp, false);
            }
        }

        protected void OnItemDataBound(object sender, DataGridItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    //Check if $amount is negative, to apply style to make amount apear in red
                    decimal amount = Math.Round(Convert.ToDecimal(e.Item.Cells[3].Text), 1);

                    if (amount < 0)
                    {
                        e.Item.Cells[3].CssClass = "DataGridNegativeCurrencyItem";
                    }
                    e.Item.Cells[3].Text = amount.ToString("c", Helper.ZeroDecimals());

                    amount = Math.Round(Convert.ToDecimal(e.Item.Cells[6].Text), 1);
                    if (amount < 0)
                    {
                        e.Item.Cells[6].CssClass = "DataGridNegativeCurrencyItem";
                    }
                    e.Item.Cells[6].Text = amount.ToString("c", Helper.ZeroDecimals());

                    amount = Math.Round(Convert.ToDecimal(e.Item.Cells[8].Text), 1);
                    if (amount < 0)
                    {
                        e.Item.Cells[8].CssClass = "DataGridNegativeCurrencyItem";
                    }
                    e.Item.Cells[8].Text = amount.ToString("c", Helper.ZeroDecimals());

                    amount = Math.Round(Convert.ToDecimal(e.Item.Cells[10].Text), 1);
                    if (amount < 0)
                    {
                        e.Item.Cells[10].CssClass = "DataGridNegativeCurrencyItem";
                    }
                    e.Item.Cells[10].Text = amount.ToString("c", Helper.ZeroDecimals());

                    amount = Math.Round(Convert.ToDecimal(e.Item.Cells[11].Text), 1);
                    if (amount < 0)
                    {
                        e.Item.Cells[11].CssClass = "DataGridNegativeCurrencyItem";
                    }
                    e.Item.Cells[11].Text = amount.ToString("c", Helper.ZeroDecimals());

                    // Paid To Date Column
                    amount = Math.Round(Convert.ToDecimal(((LinkButton) e.Item.Cells[12].Controls[0]).Text), 1);
                    if (amount < 0)
                    {
                        e.Item.Cells[12].CssClass = "DataGridNegativeCurrencyItem";
                    }
                    LinkButton lb = (LinkButton) e.Item.Cells[12].Controls[0];
                    string lbText = amount.ToString("c", Helper.ZeroDecimals());
                    lb.Text = lbText;
                    lb.Enabled = (lbText != Constant.ZeroDollarsNoCents);
                }
                else if (e.Item.ItemType == ListItemType.Footer)
                {
                    DataTable totals = SalaryDistributions.GetDataContainer().Tables[SalaryDistributions.TotalsTableName];

                    if ((totals != null) && (totals.Rows.Count != 0))
                    {
                        DataRow dr = totals.Rows[0];

//						e.Item.Cells[3].Text = (Convert.ToDecimal(dr[TotalAnnualRate])).ToString("c", PHSRAG.WebControls.Helper.ZeroDecimals());
//						e.Item.Cells[6].Text = (Convert.ToDecimal(dr[TotalMonthlyRate])).ToString("c", PHSRAG.WebControls.Helper.ZeroDecimals());
                        e.Item.Cells[8].Text = (Convert.ToDecimal(dr[TotalCommittedSalary])).ToString("c", Helper.ZeroDecimals());
                        e.Item.Cells[10].Text = (Convert.ToDecimal(dr[TotalCommittedFringe])).ToString("c", Helper.ZeroDecimals());
                        e.Item.Cells[11].Text = (Convert.ToDecimal(dr[TotalTotalCommitted])).ToString("c", Helper.ZeroDecimals());
                        e.Item.Cells[12].Text = (Convert.ToDecimal(dr[TotalPaidToDate])).ToString("c", Helper.ZeroDecimals());
                    }
                }
            }
            catch (Exception ex)
            {
                annunciator.Message = String.Format("{0} while attempting to format columns."
                    , ExceptionReport.GetExceptionInfo(ex, false));
            }
        }

        protected void OndataGridItemCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    if (e.CommandName == CommandName)
                    {
                        Hashtable dictionary = new Hashtable();

                        dictionary.Add(Constant.PageNameKey, "Salaries");
                        dictionary.Add(Constant.PersonnelConstants.EmployeeJobMapIDKey, Convert.ToInt32(e.Item.Cells[15].Text));

                        dictionary.Add(Constant.FundNumberKey, e.Item.Cells[2].Text);

                        pageCachePolicy.Cache(Keys.IncomingDataKey, dictionary);
                        PurgeCache();
                        Response.Redirect
                            (Settings.GetKeyValue("SubNavigation.Personnel.LaborDistributionURL", string.Empty), false);
                    }
                }
            }
            catch (Exception excp)
            {
                annunciator.Message = ExceptionReport.GetExceptionInfo(excp, false);
            }
        }

        #endregion

        #region Search Control Events

        /// <summary>
        /// Event handler for the Search event raised by the CommonSearch control. Gets the search criteia.
        /// </summary>
        /// <param name="args">Argument associated with the event (contains the search criteria dictionary)</param>
//		public void OnSearch(SearchCriteriaArgs args)
        public override void OnSearch(SearchCriteriaArgs args)
        {
            try
            {
                CurrentPageIndex = 0;
                LoadDataGrid();
                annunciator.Message = string.Empty;
                annunciator.Title = string.Empty;
            }
            catch (Exception excp)
            {
                annunciator.Message = ExceptionReport.GetExceptionInfo(excp, false);
            }
        }

        /// <summary>
        /// Handler for the event raised by the CommonSearch control when the "Clear Selection" buttion is clicked upon.
        /// The control clears the criretria (specific to this module).
        /// Since in the page life-cycle, the Load occurs before the Clear event, we have to instigate a re-load of the
        /// data grid to refelect the fact that the search criteria has been cleared.
        /// </summary>
        /// <param name="e">Argument associated with the event</param>
//		public void OnClearSelection(CommandEventArgs e)
        public override void OnClearSelection(CommandEventArgs e)
        {
            SearchCriteriaVersion = -1;
            ManagePagination();
            annunciator.Message = string.Empty;
            annunciator.Title = string.Empty;
        }

        #endregion

        #region Sort

        protected void OnSort(object source, DataGridSortCommandEventArgs e)
        {
            try
            {
                if (e.SortExpression != string.Empty)
                {
                    SalaryDistributions.Sort(e.SortExpression);
                    CurrentPageIndex = 0;
                    LoadDataGrid();
                }
            }
            catch (Exception excp)
            {
                annunciator.Message = ExceptionReport.GetExceptionInfo(excp, false);
            }
        }

        #endregion

        #region OnHeaderNavigate

        /// <summary>
        /// Resets the Agreements subnavigation selected link before the 
        /// header performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void OnHeaderNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                PurgeCache();
                agreementsSubNavigation.Reset();
                agreementDetailsSubNavigation.Reset();
            }
            catch (Exception excp)
            {
                annunciator.Message = ExceptionReport.GetExceptionInfo(excp, false);
            }
        }

        /// <summary>
        /// Purges the cache before the agreements subnavigation header performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void OnSubNavigate(object sender, CommandEventArgs e)
        {
            PurgeCache();
        }

        /// <summary>
        /// Purges the cache before the agreement details subnavigation header performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void OnDetailsSubNavigate(object sender, CommandEventArgs e)
        {
            PurgeCache();
        }

        #endregion

        #endregion

        #region Private Methods

        /// <summary>
        /// Manages the Page Control links to support pagination based on the CurrentPageIndex
        /// </summary>
        private void ManagePagination()
        {
            pagerBelowDatagrid.Visible = pagerAboveDatagrid.Visible = dataGrid.Visible = (dataGrid.Items.Count > 0 && SearchCriteriaVersion != -1);
            if (dataGrid.Visible)
            {
                int currentPageIndex = CurrentPageIndex;
                dataGrid.CurrentPageIndex = currentPageIndex;

                int startIndex = currentPageIndex*dataGrid.PageSize;

                pagerBelowDatagrid.FirstRecord = pagerAboveDatagrid.FirstRecord = startIndex + 1;
                pagerBelowDatagrid.LastRecord = pagerAboveDatagrid.LastRecord =
                    Math.Min(startIndex + dataGrid.PageSize, SalaryDistributions.Count);

                pagerBelowDatagrid.EnableFirstPage = pagerAboveDatagrid.EnableFirstPage =
                    pagerBelowDatagrid.EnablePreviousPage = pagerAboveDatagrid.EnablePreviousPage =
                        (CurrentPageIndex != 0);

                pagerBelowDatagrid.EnableLastPage = pagerAboveDatagrid.EnableLastPage =
                    pagerBelowDatagrid.EnableNextPage = pagerAboveDatagrid.EnableNextPage =
                        (CurrentPageIndex != (pagerAboveDatagrid.PageCount - 1));
            }
        }

        /// <summary>
        /// Loads the datagrid with data.  Throws exception when no data is found.
        /// </summary>
        private void LoadDataGrid()
        {
            SalaryDistributions salaryDistributions = SalaryDistributions;

            dataGrid.VirtualItemCount = pagerBelowDatagrid.RecordCount = pagerAboveDatagrid.RecordCount = salaryDistributions.Count;

            int currentPageIndex = CurrentPageIndex;

            int pageCount = (pagerAboveDatagrid.RecordCount/dataGrid.PageSize) +
                (((pagerAboveDatagrid.RecordCount%dataGrid.PageSize) == 0) ? 0 : 1);

            pagerBelowDatagrid.PageCount = pagerAboveDatagrid.PageCount = pageCount;
            pagerBelowDatagrid.CurrentPage = pagerAboveDatagrid.CurrentPage = currentPageIndex + 1;

            dataGrid.DataSource = salaryDistributions.GetSalaryDistributionList(currentPageIndex*dataGrid.PageSize, dataGrid.PageSize);
            dataGrid.DataBind();

            pagerBelowDatagrid.Visible = pagerAboveDatagrid.Visible = dataGrid.Visible = (dataGrid.Items.Count > 0);
            if (dataGrid.Visible)
            {
                ManagePagination();
            }
            else
            {
                throw new Exception("No Information found. Try again with different Search criteria.");
            }
        }

        /// <summary>
        /// Adds refresh dates currently visible on the page to the search criteria string
        /// to be passed down to reports. The criteria does not persist to the SearchCriteria
        /// object.
        /// </summary>
        /// <param name="searchCriteria">Object containing search criteria.</param>
        /// <returns>A string representation of search criteria. </returns>
        private string AddRefreshDatesToCriteria(SearchCriteria searchCriteria)
        {
            StringBuilder criteria = new StringBuilder(searchCriteria.ToString(";"));
            if (refreshDates.SalaryAsOfDateVisible)
            {
                criteria.AppendFormat("Last Salary Post|{0};", refreshDates.SalaryAsOfDate.ToShortDateString());
            }
            if (refreshDates.GLAsOfDateVisible)
            {
                criteria.AppendFormat("Last GL Post|{0};", refreshDates.GLPostAsOfDate.ToShortDateString());
            }
            if (refreshDates.POAPAsOfDateVisible)
            {
                criteria.AppendFormat("Last PO/AP Post|{0};", refreshDates.POAPAsOfDate.ToShortDateString());
            }
            return criteria.ToString();
        }

        /// <summary>
        /// Uncaches all objects with data for this page. Also syncs up the search criteria
        /// number and the one stored on the page cache to ensure database does not inadvertently
        /// get hit when accessing page's BO properties due to version number changes.
        /// </summary>
        private void PurgeCache()
        {
            ResultsCache.PurgeObject(cachePolicy);
        }

        #endregion

        #region Web Form Designer generated code

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);

            cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];

            string referringPage = Path.GetFileName(Request.UrlReferrer.LocalPath);

            if (referringPage == InsightUtilities.Constants.ModulePages.AgreementSummary || referringPage == InsightUtilities.Constants.ModulePages.FinancialSummary)
            {
                ReferingSummaryPage = referringPage;
            }
            else
            {
                ReferingPage = referringPage;
            }
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
        }

        #endregion
    }
}